package cn.xxstudy.blog.controller

import cn.xxstudy.blog.bean.BlogQuery
import cn.xxstudy.blog.service.BlogService
import cn.xxstudy.blog.service.CategoryService
import javassist.NotFoundException
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.crossstore.ChangeSetPersister
import org.springframework.data.domain.Pageable
import org.springframework.data.domain.Sort
import org.springframework.data.web.PageableDefault
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable

/**
 * 作者：wuxinxi on 2020/11/27
 * 包名：cn.xxstudy.blog.controller
 * TODO:分类
 */
@Controller
class CategoryController {
    companion object {
        private const val BLOG_CATEGORY = "category"
    }

    @Autowired
    private lateinit var categoryService: CategoryService

    @Autowired
    private lateinit var blogService: BlogService

    @GetMapping("/$BLOG_CATEGORY/{id}")
    fun getCategory(@PageableDefault(size = 5, sort = ["updateDateTime"], direction = Sort.Direction.DESC) pageable: Pageable,
                    @PathVariable id: Long = -1, model: Model): String {
        val categoryList = categoryService.listCategoryTop(1000)
        if (categoryList.isEmpty()) {
            throw NotFoundException("还没有任何分类哦")
        }
        var categoryId = id
        if (categoryId == -1L) {
            categoryId = categoryList[0].id
        }
        model.addAttribute("categoryList", categoryList)
        val query = BlogQuery(categoryId = categoryId)
        model.addAttribute("categoryBlogListPage", blogService.listBlog(false,pageable, query))
        model.addAttribute("selectId", categoryId)
        return BLOG_CATEGORY
    }
}